package com.zzx.shiro.controller;

import com.zzx.shiro.entity.User;
import com.zzx.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName: UserController
 * @Description: 用户Controller
 * @Author zhouzhixin
 * @Date 2021/9/13
 * @Version 1.0
 */
@RequestMapping("/user")
@Controller
public class UserController {

    UserService userService;

    /**
     * 配置自动注入方法
     *
     * @param userService
     */
    @Autowired
    public void init(UserService userService) {
        this.userService = userService;
    }

    /**
     * <p>登录接口</p>
     *
     * @param username
     * @param password
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/15 17:36
     */
    @PostMapping(value = "/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        User user = userService.queryByUserName(username);
        if (null == user) {
            model.addAttribute("tip", "1");
            return "login";
        }
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        token.setRememberMe(true);
        // 执行认证登陆
        subject.login(token);
        if (subject.isAuthenticated()) {
            return "index";
        } else {
            token.clear();
            throw new AuthenticationException("登录失败");
        }
    }

    /**
     * <p>权限测试方法1</p>
     *
     * @param
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/15 17:36
     */
    @ResponseBody
    @GetMapping("/show")
    public String showUser() {
        return "这是学生信息";
    }

    /**
     * <p>权限测试方法2</p>
     *
     * @param
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/15 17:36
     */
    @RequiresPermissions("user:delete")
    @ResponseBody
    @GetMapping("/delete")
    public String deleteUser() {
        return "您删除了一条用户信息";
    }

}

